package com.fastdfs.demo.controller;

import com.fastdfs.demo.dto.RestResult;
import com.fastdfs.demo.dto.ResultUtil;
import com.fastdfs.demo.service.FastDFSFileUtil;
import com.fastdfs.demo.util.DateUtil;
import com.fastdfs.demo.util.OfficeUtil;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Date;

@RestController
@RequestMapping("/file")
public class FileController {

    @Value("${file.tmpPath:/tmp}")
    private String tmpPath; // 本地临时文件路径
    @Value("${fdfs.fileUrl}")
    private String fileUrl; // Nginx访问FastDFS中文件的路径

    /**
     * fastdfs上传文件
     *
     * @param file 文件
     * @return
     * @throws IOException
     */
    @PostMapping("/fastdfs/upload")
    public RestResult<String> fastdfsUpload(MultipartFile file) throws IOException {
        // MultipartFile对象不能再服务间传递，必须转为byte数组
        byte[] fileBytes = file.getBytes();
        String fileName = file.getOriginalFilename();
        String prefix = DateUtil.dateToStr(new Date(), DateUtil.DATE_FORMAT_7);
        String imageUrl = "";
        String localFileName = "";
        if (fileBytes.length != 0) {
            try {
                // 1.将文件字节数组转为输入流
//                InputStream inputStream = new ByteArrayInputStream(fileBytes);

                // 2.获取文件的后缀名
                String fileSuffix = fileName.substring(fileName.lastIndexOf(".") + 1);
                localFileName = tmpPath + "/" + prefix + "." + fileSuffix;
                file.transferTo(new File(localFileName));
                // 3.上传文件
                String[] strs = FastDFSFileUtil.upload(localFileName, fileSuffix);
                if(strs==null){
                    return ResultUtil.fail("上传失败");
                }
                // 4.返回图片路径
                //imageUrl = fileUrl + "/" + storePath.getFullPath();
                imageUrl =  fileUrl + "/" + strs[0] + "/" + strs[1];
            } catch (Exception e) {
                e.printStackTrace();
                return ResultUtil.fail("上传失败");
            }finally {
                OfficeUtil.delete(localFileName);
            }
        } else {
            return ResultUtil.fail("上传失败");
        }
        return ResultUtil.success(imageUrl);
    }
    /**
     * fastdfs删除文件
     *
     * @param groupName 桶名
     * @param remoteName 文件路径
     * @return
     */
    @PostMapping("/fastdfs/delete")
    public RestResult fastdfsDelete(String groupName, String remoteName) {
        Integer delete = FastDFSFileUtil.delete(groupName, remoteName);
        if(delete==0){
            return ResultUtil.success("ok");
        }else{
            return ResultUtil.fail(delete+"");
        }

    }
//    /**
//     * fastdfs下载文件
//     *
//     * @param filePath 文件路径
//     * @return
//     */
//    @GetMapping("/fastdfs/download")
//    public void fastdfsDownLoad(String filePath) throws IOException {
//        //http://ip:8888/group1/M00/00/00/rBoX5mR0ulSAIukOAASzmDL13HM352.jpg
//        byte[] bytes = null;
//        try {
//            //返回"/"第三次出现的位置
//            int index1 = StringUtils.ordinalIndexOf(filePath,"/",3);
//            int index2 = StringUtils.ordinalIndexOf(filePath,"/",4);
//            String group = filePath.substring(index1+1,index2);
//            String filepath = filePath.substring(filePath.lastIndexOf(group + "/")+7);
//            DownloadByteArray callback = new DownloadByteArray();
//            bytes = fastFileStorageClient.downloadFile(group, filepath,callback);
//            //文件输出流
//            FileOutputStream fileOutputStream = new FileOutputStream("D:\\A多媒体\\图库\\fastdfs");
//            fileOutputStream.write(bytes);
//            fileOutputStream.flush();
//            fileOutputStream.close();
//        }
//        catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
}